//
//  DFHomeViewController.swift
//  FlyBlog
//
//  Created by FEI on 16/4/8.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh

class DFHomeViewController: DFBaseViewController {

    private lazy var pullDownRefreshControl: DFPullDownRefreshControl = DFPullDownRefreshControl()
    var statuses: [DFStatus]? {
        didSet{
            self.tableView.reloadData()
        }
    }

    private let Reuseidentifier = "Reuseidentifier"
    override func viewDidLoad() {
        super.viewDidLoad()
        if !DFUserAccountModel.shareInstance.userLogin {
            return
        }
        self.setupNavigationBar()

        prepareTableView()


//        DFStatusViewModel.shareInstance.loadStatus { (statuses, error) -> () in
//            if error != nil{
//                return
//        }
//       }
    }

    private func prepareTableView() {

        tableView.addSubview(pullDownRefreshControl)

        pullDownRefreshControl.pullDownRefreshHandler = { () -> () in
            DFPrint("控制器开始下拉刷新")
            self.loadNewStatus()

//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//                DFPrint("下拉刷新完成,获得到了数据")
//                // 让刷新控件完成刷新,切换到Normal状态
//                self.pullDownRefreshControl.endRefreshing()
//            })
        }

        pullDownRefreshControl.startRefreshing()

        tableView.registerClass(DFStatusCell.self, forCellReuseIdentifier: Reuseidentifier)

        tableView.rowHeight = UITableViewAutomaticDimension

        tableView.estimatedRowHeight = 200

        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreStatus()
        }


    }

    private func loadMoreStatus() {
        let max_id = self.statuses?.last?.id ?? 0
        if max_id == 0 {
            return
        }

        DFStatusViewModel.shareInstance.loadStatus(0, max_id: max_id - 1) { (statuses, error) -> () in
            self.tableView.infiniteScrollingView.stopAnimating()

            if error != nil {
                return
            }

            let count = statuses?.count ?? 0

            if count == 0 {
                SVProgressHUD.showErrorWithStatus("没有加载更多数据了")
                return
            }

            let s = self.statuses! + statuses!
            self.statuses = s
        }

    }

    private func loadNewStatus() {
        let since_id = self.statuses?.first?.id ?? 0


        DFStatusViewModel.shareInstance.loadStatus (since_id, max_id: 0) { (statuses, error) -> () in

            self.pullDownRefreshControl.endRefreshing()
            if error != nil {
                SVProgressHUD.showErrorWithStatus("你的网络不给力")
                return

            }

            let count = statuses?.count ?? 0

            if since_id != 0 {
                self.showTipLabel(count)

            }

            if count == 0 {
//                if since_id == 0 {
//
//                }
                return
            }

            if since_id == 0 {
                self.statuses = statuses
            }else {
                let s = statuses! + self.statuses!
                self.statuses = s
            }
        }

    }

    private func showTipLabel(count: Int) {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center

        let y = -(UIApplication.sharedApplication().statusBarFrame.height + 44)
        label.frame = CGRectMake(0, y, UIScreen.mainScreen().bounds.width, 44)
        label.text = count == 0 ? "没有新的微博数据" : "下拉刷新了\(count)条微博数据"

        navigationController?.navigationBar.insertSubview(label, atIndex: 0)

        UIView.animateWithDuration(1,animations:{ () -> Void in
            label.frame = CGRectMake(0, 44, UIScreen.mainScreen().bounds.width, 44)
            }) { (_) -> Void in
                UIView.animateWithDuration(1,delay: 0.5,options: [], animations: { () -> Void in
                    label.frame = CGRectMake(0, -(UIApplication.sharedApplication().statusBarFrame.height + 44), UIScreen.mainScreen().bounds.width, 44)
                    } , completion: { (_) -> Void in
                        label.removeFromSuperview()

                })
    }
}
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: Selector("didClickAdd:"))

        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: Selector("didClickQRCode:"))

        let name = DFUserAccountModel.shareInstance.userAccount?.screen_name ?? "没有名称"

        //自定义标题栏按钮
        let titleButton = DFHomeTitleButton(title: name)
        titleButton.addTarget(self, action: Selector("didClickTitleButton:"), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
        
    }

    @objc private func didClickTitleButton(button: UIButton) {
        DFPrint("----")
       button.selected = !button.selected
    UIView.animateWithDuration(0.25) { () -> Void in
        button.imageView?.transform = button.selected ?
        CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity

        }
    
    }

    @objc private func didClickAdd(button: UIButton) {
        DFPrint("添加朋友")
    }

    @objc private func didClickQRCode(button: UIButton) {
        DFPrint("二维码")
    }

}

extension DFHomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statuses?.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(Reuseidentifier,forIndexPath: indexPath) as! DFStatusCell
        cell.status = self.statuses?[indexPath.row]

//        cell.textLabel?.text = self.statuses![indexPath.row].text
        return cell
    }

    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}
